package com.why.sharding.service;

import com.why.sharding.dao.UserDao;
import com.why.sharding.entity.User;
import com.why.sharding.util.SnowflakeIdWorker;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: wanghongyu | stan.wang@paytm.com
 * @create: 2022/01/19
 **/
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = {Exception.class})
public class UserService {

    private final UserDao userDao;

    /**
     * 功能描述： 根据用户流水ID来删除用户
     * @param userId
     */
    public void deleteUser(Long userId){
        userDao.deleteByPrimaryKey(userId);
    }

    /**
     * 功能描述： 更新用户流水ID
     *
     * @param user 用户实体
     * @return 返回更新结果
     */
    public User updateUser(User user) {
        userDao.updateByPrimaryKeySelective(user);
        return user;
    }

    /**
     * 功能描述： 根据用户名称和用户密码查询用户数据
     *
     * @param user 用户信息
     * @return 返回查询结果
     */
    public User queryUser(User user) {
        return userDao.queryUser(user);
    }

    /**
     * 功能描述： 实现新增用户
     *
     * @param user 用户实体
     * @return 返回新增的结果
     */
    public User saveUser(User user) {
        int modelVal = (int) (user.getUserId() % 4);
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(4, modelVal, 1L, 1L);
        user.setUserId(snowflakeIdWorker.nextId());
        userDao.insertSelective(user);
        return user;
    }

}

